from flask import request,Response
from db import Users,db,app
import json


@app.route('/users')
def get_users():
    users = Users.query.all()  # 查询所有用户
    results =  {
        'users': [{'id': u.id, 'username': u.username} for u in users]
    }

    return Response(
        json.dumps(results, ensure_ascii=False),
        content_type='application/json; charset=utf-8'
    )


@app.route('/add_user', methods=['POST'])
def add_user():
    data = request.json # 接受前端的数据,必须json格式
    new_user = Users(username=data['username'], email=data['email'])
    db.session.add(new_user)
    db.session.commit()  # 提交事务
    return {'message': 'User created'}, 201

if __name__ == '__main__':
    app.run(debug=True)